import {
  apiAndPCType,
  apiType,
  Box3Get,
  Box3Put,
  escapeHtml,
} from "@ap/util/request";
import * as vscode from "vscode";
import {
  showErrorMessage,
  showInformationMessage,
} from "@ap/util/vscode/message";
import { auth } from "@ap/util/request";
import { updatePackageJson, getPackageJson } from "@ap/util/packageJson";
import { arenaErrorMsg } from "@ap/util/vscode/errorMsg";
import { CommandId, tempChatEditMap } from "@ap/command";
import insertCode from "@ap/util/vscode/insertCode";
import { PackageConfig } from "@ap/types/config";
import openInternetImage from "@ap/webView/img";

export interface ExtendedQuickPickItem extends vscode.QuickPickItem {
  type?: number;
  view?: string;
}

/**
 * 异步获取扩展地图列表数组。
 * @returns 返回承诺，解析为数据项数组。
 */
export async function getBox3MapTempChatList(): Promise<
  ExtendedQuickPickItem[] | undefined
> {
  return getPackageJson<PackageConfig>("map").then(async (packageJson) => {
    if (packageJson) {
      const mapId = packageJson.id;
      if (mapId) {
        const requestOptions = {
          url: "engine/chat/temp/ids?mode=edit&mapId=" + mapId,
        };
        /**
         * 发送请求并等待响应。
         */
        const response = await Box3Get(requestOptions, "地图临时聊天房间");
        /**
         * 检查响应是否成功，如果不成功则返回错误消息。
         */
        if (!response || response.code !== 200) {
          showErrorMessage(`获取地图临时聊天频道失败: ${response.msg}`);
          return;
        }
        /**+
         * 处理响应数据，映射物品到数据项格式，并转义HTML字符以防止XSS攻击。
         */
        const dataSource: ExtendedQuickPickItem[] = response.data.map(
          (item: string) => ({
            label: item,
          }),
        );
        tempChatEditMap.description = `共${dataSource.length}项`;
        return dataSource;
      }
    }
  });
}

export default async function selectBox3MapTempChatDetail(
  modal: ExtendedQuickPickItem,
) {
  try {
    const requestOptions = {
      url: "engine/chat/temp/users?tempChatId=" + modal.label,
    };
    /**
     * 发送请求并等待响应。
     */
    const response = await Box3Get(requestOptions, "地图临时聊天房间玩家");
    /**
     * 检查响应是否成功，如果不成功则返回错误消息。
     */
    if (!response || response.code !== 200) {
      showErrorMessage(`获取地图临时聊天频道玩家列表失败: ${response.msg}`);
      return;
    }
    const dataSource: ExtendedQuickPickItem[] = response.data.map(
      (item: string) => ({
        label: item,
      }),
    );
    const selectedOption = await vscode.window.showQuickPick(dataSource, {
      title: `《${modal.label}》频道操作`,
      placeHolder: "当前共" + String(dataSource.length) + "位玩家",
      matchOnDescription: true,
      canPickMany: false,
    });

    if (selectedOption) {
      vscode.env.openExternal(
        vscode.Uri.parse(
          apiAndPCType[apiType].pc + "profile/" + selectedOption.label,
        ),
      );
    }
  } catch (error) {
    // 处理可能的用户取消操作或其他异常
    showErrorMessage(`选择操作遇到错误: ${error}`);
  }
}
